package top.yangyitao.util;

import java.util.List;

import top.yangyitao.model.JsonChess;
import top.yangyitao.model.Manual;
import top.yangyitao.model.Point;

public class MachineLearningUtil {
	public static boolean EqualLearnArea(int[][] chessBoard,int [][]LearnArea,Point P){
		for(int i=0;i<5;++i){
			for(int j=0;j<5;++j)
				if(chessBoard[i+P.getY()][j+P.getX()]!=LearnArea[i][j])
					return false;
		}
		return true;
	}
	public static Point readAcknowlage(int [][]chessBoard,List<Manual> manuals) {

		Point p=null;
		int [][]Area=new int[5][5];
			for(Manual manual: manuals){
				for(int i=0;i<25;++i)
					Area[i/5][i%5]=manual.getManualArray()[i];
				int y=manual.getManualArray()[25];
				int x=manual.getManualArray()[26];
				for(int i=0;i<10;++i)
					for(int j=0;j<10;++j)
						if(EqualLearnArea(chessBoard,Area,new Point(i,j))==true){
							return new Point(x+j,y+i);
						}
			}		
		return p;
	}
	public static Point getStartPoint(int[][] chessBoard, Point p){
		int[][] shift = {{1,0},{1,1},{0,1},{1,-1}};
		Point startPoint;
		for(int k=0;k<4;k++)
			if(MonteCarlo.getPointLinkLength(chessBoard, p, shift[k][0], shift[k][1], 1,false)+MonteCarlo.getPointLinkLength(chessBoard, p, shift[k][0], shift[k][1], -1,false)+1>=5){			
				int len=MonteCarlo.getPointLinkLength(chessBoard, p, shift[k][0], shift[k][1], -1,false);
				startPoint=new Point(p.getX()-len*shift[k][1],p.getY()-len*shift[k][0]);
				
				if(k==3) 
					startPoint.setX(startPoint.getX()-5);				
				if(startPoint.getX()+5>=15)
					startPoint.setX(startPoint.getX()-5);
				if(startPoint.getY()+5>=15)
					startPoint.setY(startPoint.getY()-5);
			
				return startPoint;
			}
		return null;
	}
	public static String SaveLearnArea(int[][] chessBoard, Point p,JsonChess[] jsonChessArray){
	
		Point startPoint;
		Point keyPoint=null;
		startPoint=getStartPoint(chessBoard,p);		
		//取LearnArea开始点
		//后退两步,取关键点,取LearnArea
		JsonChess[] pos=jsonChessArray;
		int backStep=2;
		int len=0;
		for(int i=0;i<pos.length&&pos[i]!=null;++i)
			len=i;
		
		for(int i=len;i>=len-backStep*2;--i)
			if(i==len-backStep*2)
				keyPoint=new Point(pos[i].getX()-startPoint.getX(),pos[i].getY()-startPoint.getY());
		
		StringBuilder manualCodeSB = new StringBuilder("");
		for(int i=0;i<5;i++)
			for(int j=0;j<5;++j)
				manualCodeSB.append(chessBoard[i+startPoint.getY()][j+startPoint.getX()]);	
		//存储关键点和LearnArea
		manualCodeSB.append(keyPoint.getY());
		manualCodeSB.append(keyPoint.getX());
		return manualCodeSB.toString();
	}
}
